<template>
  <div
    class="input"
    ref="outer"
    :style="props.style">
    <label
      ref="label"
      for="input"
      class="input-label">
      <slot></slot>
    </label>
    <input
      v-if="props.type === 'input'"
      @focus="foucusHandler"
      @blur="blurHandler"
      @input="changeInput"
      type="text"
      name="input"
      v-model="value"
      :placeholder="props.placeholder"
      maxlength=""
      autocomplete="off"
      class="input-text" />
    <textarea
      v-if="props.type === 'textarea'"
      @focus="foucusHandler"
      @blur="blurHandler"
      @input="changeInput"
      name="input"
      v-model="value"
      style="resize: vertical"
      :placeholder="props.placeholder"
      maxlength=""
      autocomplete="off"
      class="input-text" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watchEffect } from 'vue'
const props = defineProps({
  style: {
    type: [String, Object]
  },
  placeholder: String,
  type: {
    type: String,
    default: 'input'
  },
  value: {
    type: String,
    default: ''
  }
})
const emits = defineEmits(['update:value'])
const value = ref<string | number>(props.value)
watchEffect(() => {
  value.value = props.value
})
const outer = ref<HTMLDivElement>()
const label = ref<HTMLLabelElement>()
const foucusHandler = () => {
  outer.value && outer.value.classList.add('input-active')
  if (label.value) label.value.style.color = '#ff6900'
}
const blurHandler = () => {
  !value.value && outer.value && outer.value.classList.remove('input-active')
  if (label.value) label.value.style.color = '#b0b0b0'
}
const changeInput = (e: Event) => {
  emits('update:value', (e.target as HTMLInputElement)!.value)
}
onMounted(() => {
  if (value.value) {
    foucusHandler()
    blurHandler()
  }
})
</script>

<style lang="less" scoped>
.input-active {
  label {
    top: -7px !important ;
    font-size: 12px !important;
    background-color: #fff !important;
  }
}
.input {
  position: relative;
  margin: 0;
  padding: 0;
  border: 0;
  text-align: left;
  .input-label {
    position: absolute;
    left: 12px;
    top: 11px;
    z-index: 2;
    padding: 0 3px;
    font-size: 14px;
    line-height: 18px;
    color: #b0b0b0;
    background: rgba(0, 0, 0, 0);
    cursor: text;
    transition: all 0.2s linear;
  }
  .input-text {
    width: 100%;
    outline: none;
    box-sizing: border-box;
    padding: 10px 16px;
    border: 1px solid #e0e0e0;
    font-size: 14px;
    line-height: 18px;
    background: #fff;
    transition: 0.2s linear;
    &:hover {
      border: 1px solid #7e7e7e;
    }
    &:focus {
      border: 1px solid #ff6900;
    }
  }
}
</style>
